package service

import (
	"grs-report-admin/model"
	"grs-report-admin/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetDataSourceList(ctx *gin.Context) {
	dataSource := model.DataSourceModel{}
	pageNo := ctx.Query("pageNo")
	pageSize := ctx.Query("pageSize")
	if pageNo == "" {
		pageNo = "1"
	}
	if pageSize == "" {
		pageSize = "10"
	}
	current, _ := strconv.Atoi(pageNo)
	size, _ := strconv.Atoi(pageSize)
	list, err := dataSource.List(current, size)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "查询失败",
			Result:  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, model.Result{
		Message: "查询成功",
		Result:  list,
	})
}
func AddDataSource(ctx *gin.Context) {
	dataSource := model.DataSourceModel{}
	if err := ctx.ShouldBindJSON(&dataSource); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "添加失败",
			Result:  err.Error(),
		})
		return
	}
	dataSource.Id = utils.GetRowId()
	if err := dataSource.Insert(); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "添加失败",
			Result:  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, model.Result{
		Message: "添加成功",
		Result:  dataSource,
	})

}
func EditDataSource(ctx *gin.Context) {
	dataSource := model.DataSourceModel{}
	if err := ctx.ShouldBindJSON(&dataSource); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "编辑失败",
			Result:  err.Error(),
		})
	}
	if err := dataSource.Update(); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "编辑失败",
			Result:  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, model.Result{
		Message: "编辑成功",
		Result:  dataSource,
	})
}
func DeleteDataSource(ctx *gin.Context) {
	dataSource := model.DataSourceModel{}
	if err := ctx.ShouldBindJSON(&dataSource); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "删除失败",
			Result:  err.Error(),
		})
	}
	if err := dataSource.Delete(); err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "删除失败",
			Result:  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, model.Result{
		Message: "删除成功",
		Result:  dataSource,
	})
}
